


var roleManage = function() {

    var _init = function() {

        var table = $('#table_role');

        table.dataTable({
            "processing": true,
            // 开启服务器模式
            serverSide: true,
            "ajax": {
                //url: "/a/sys/roles", // 列表查询
            	url:url+"s",
                // data: json
            },
            "autoWidth": false,
            "columns": [{
                    "width": "20%",
                    "data": "name"
                },{
                    "width": "15%",
                    "data": "minCount"
                },
                {
                    "width": "20%",
                    "data": "createDate"
                },
                {
                    "width": "20%",
                    "data": "null",
                    "defaultContent": "<button type=\"button\" class=\"btn blue btn_edit_role\">修改</button><button type=\"button\" class=\"btn red btn_del_role\">删除</button>"
                }
            ],
            "language": {
                "lengthMenu": "每页显示 _MENU_ 条记录",
                "emptyTable": "暂无数据记录",
                "info": "显示 _START_ 至 _END_ 条数据，共 _TOTAL_ 条记录！",
                "zeroRecords": "没有搜索到匹配记录",
                "infoEmpty": "",
                "infoFiltered": "",
                "processing": "数据加载中,请稍后..."
            },
            "pageLength": 5,
            "order": [
                [2, "desc"]
            ],
            "columnDefs": [{
                "orderable": false,
                "targets": [0, 3]
            }, {
                "targets": 2,
                "render": function(data, type, row, meta) {
                    return moment(data).format('YYYY-MM-DD HH:mm');
                }
            }],
            "dom": "<'row'<'.col-md-6 col-sm-12'><'col-md-6 col-sm-12'>r>" +
                "<t>" +
                "<'row'<'col-md-5'i><'col-md-7'>p>",
            "fnInitComplete": function() {}
        });

        // 关闭弹框
        $(".modal").on('hidden.bs.modal', function(e) {
            $('.modal .alert').css('display', 'none'); // 隐藏提示头
            $('.modal .form-group').removeClass('has-error'); //清除错误信息
            $('.modal input[type="text"]').val(''); // 清空 input
            $('.modal input[type="checkbox"]').prop('checked', false); // 清空 input
            $(' .help-block').html(''); 
        });
        // 添加
        $('#btn_new_role').click(function(event) {
//        	$.get("/a/biz/alevel/edit?id="+null);
            $('#modal_new_role').modal('show');
            
            $("#modal_new_role input[name='minCount']").val('');
        });

        // 修改
        table.on('click', '.btn_edit_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            var _name = oData_arr[0].name;
            $('#modal_edit_role').find('input[type=hidden]').val(_id);
            $('#modal_edit_role [name="name"]').val(_name);
            $('#modal_edit_role [name="minCount"]').val(oData_arr[0].minCount);
            $('#modal_edit_role [name="minCash"]').val(oData_arr[0].minCash);

            $('#modal_edit_role').modal('show');
        });

        $('#doQuery').click(function(event){
    		  var name =   $("#search input[name='name']").val();
    		  var start =   $("#datepicker input[name='start']").val();
    		  var end =   $("#datepicker input[name='end']").val();
    		  var param={"name":name,"createDate":start,"updateDate":end};
    		  $('#table_role').DataTable().search(JSON.stringify(param)  ).draw();
    			$(' .help-block').html(''); 
//            table.DataTable().ajax.reload();

    		  
    		});
        
        // 删除
        table.on('click', '.btn_del_role', function(event) {
            var oData_arr = table.DataTable().rows($(this).parents("tr"))
                .data(); // 操作行对象
            var _id = oData_arr[0].id;
            bootbox.dialog({
                message: "确定要删除",
                title: "提示",
                buttons: {
                    cancel: {
                        label: "取消",
                        className: "btn dark btn-outline"
                    },
                    success: {
                        label: "确定",
                        className: "btn green",
                        callback: function() {
                            // alert('提交删除');
                            var _data = JSON.stringify({ id: _id });
                            request_role_del(_data, function(res) {
                                // 正确
                                table.DataTable().ajax.reload();
                                $(' .help-block').html(''); 
                            }, function(err) {
                                //	错误
                            	$(' .help-block').html(err); 
                        		$(' .help-block').css('color','red'); 
                            })
                        }
                    }
                }
            });
        });
    }

    return {
        init: function() {
            _init();
        }

    };

}();


$('#qBeginTime').datepicker({  
    todayBtn : "linked",  
    autoclose : true,  
    todayHighlight : true,  
    endDate : new Date()  
}).on('changeDate',function(e){  
    var startTime = e.date;  
    $('#qEndTime').datepicker('setStartDate',startTime);  
});  
//结束时间：  
$('#qEndTime').datepicker({  
    todayBtn : "linked",  
    autoclose : true,  
    todayHighlight : true,  
    endDate : new Date()  
}).on('changeDate',function(e){  
    var endTime = e.date;  
    $('#qBeginTime').datepicker('setEndDate',endTime);  
});


var roleForm = function() {

    // 新建表单验证
    var validate_role_new = function() {

        var form_new = $('#form_role_new');
        var error_new = $('.alert-danger', form_new);
        var success_new = $('.alert-success', form_new);
        var server_error_new = $('.alert-warning', form_new);

        form_new.validate({
            errorElement: 'span',
            errorClass: 'help-block help-block-error',
            focusInvalid: false,
            ignore: "", // 不验证隐藏input
            rules: {
                name: {
                    required: true
                },
                minCount: {
                    required: true
                },
                minCash: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "请输入代理级别名称"
                },
                minCount: {
                    required: "请输入代理套数"
                }
               
            },

            errorPlacement: function(error, element) {
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element);
                }
            },

            invalidHandler: function(event, validator) {
                success_new.hide();
                server_error_new.hide();
                error_new.show();
            },

            highlight: function(element) {
                $(element)
                    .closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element)
                    .closest('.form-group').removeClass('has-error');
            },

            success: function(label) {
                label
                    .closest('.form-group').removeClass('has-error');
            },

            submitHandler: function(form) {
                success_new.show();
                error_new.hide();
                server_error_new.hide();
                $(form).find('button[type=submit]').attr('disabled', 'disabled');

                var _data = JSON.stringify($(form).serializeObject());

                request_role_new(_data, function(res) {
                    // 正确
                    $("#table_role").DataTable().ajax.reload(); // 刷新table
                    $('#modal_new_role').modal('hide');
                    $(form).find('button[type=submit]').removeAttr('disabled');      
                    $(' .help-block').html(''); 
                }, function(err) {
                    //	错误
                    success_new.hide();
                    server_error_new.show();
                    server_error_new.html(err);
                    $(form).find('button[type=submit]').removeAttr('disabled');
                })

                return false;
            }
        });
    }

    // 编辑表单验证
    var validate_role_edit = function() {

        var form_edit = $('#form_role_edit');
        var error_edit = $('.alert-danger', form_edit);
        var success_edit = $('.alert-success', form_edit);
        var server_error_edit = $('.alert-warning', form_edit);

        form_edit.validate({
            errorElement: 'span',
            errorClass: 'help-block help-block-error',
            focusInvalid: false,
            ignore: "", // 不验证隐藏input
            
            rules: {
                name: {
                    required: true
                },
                minCount: {
                    required: true
                },
                minCash: {
                    required: true
                }
            },
            messages: {
                name: {
                    required: "请输入代理级别名称"
                },
                minCount: {
                    required: "请输入代理套数"
                }
            },
            

            errorPlacement: function(error, element) {
                if (element.parent(".input-group").size() > 0) {
                    error.insertAfter(element.parent(".input-group"));
                } else if (element.attr("data-error-container")) {
                    error.appendTo(element.attr("data-error-container"));
                } else if (element.parents('.radio-list').size() > 0) {
                    error.appendTo(element.parents('.radio-list').attr("data-error-container"));
                } else if (element.parents('.radio-inline').size() > 0) {
                    error.appendTo(element.parents('.radio-inline').attr("data-error-container"));
                } else if (element.parents('.checkbox-list').size() > 0) {
                    error.appendTo(element.parents('.checkbox-list').attr("data-error-container"));
                } else if (element.parents('.checkbox-inline').size() > 0) {
                    error.appendTo(element.parents('.checkbox-inline').attr("data-error-container"));
                } else {
                    error.insertAfter(element);
                }
            },

            invalidHandler: function(event, validator) {
                success_edit.hide();
                server_error_edit.hide();
                error_edit.show();
            },

            highlight: function(element) {
                $(element)
                    .closest('.form-group').addClass('has-error');
            },

            unhighlight: function(element) {
                $(element)
                    .closest('.form-group').removeClass('has-error');
            },

            success: function(label) {
                label
                    .closest('.form-group').removeClass('has-error');
            },

            submitHandler: function(form) {
                success_edit.show();
                error_edit.hide();
                server_error_edit.hide();
                $(form).find('button[type=submit]').attr('disabled', 'disabled');

                var _data = JSON.stringify($(form).serializeObject());

                request_role_edit(_data, function(res) {
                    // 正确
                    $("#table_role").DataTable().ajax.reload(); // 刷新table
                    $('#modal_edit_role').modal('hide');
                    $(form).find('button[type=submit]').removeAttr('disabled');
                    $(' .help-block').html(''); 
                    
                }, function(err) {
                    //	错误
                	success_edit.hide();
                	server_error_edit.show();
                	server_error_edit.html(err);
                    $(form).find('button[type=submit]').removeAttr('disabled');
                })

                return false;
            }
        });
    }

    return {
        init: function() {
            validate_role_new();
            validate_role_edit();
        }

    };
}();

$(function() {
    roleManage.init();
    roleForm.init();
});